package fr.uniscol.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import fr.uniscol.dao.IUserDao;
import fr.uniscol.model.utilisateur.ProfilUtilisateur;
import fr.uniscol.model.utilisateur.User;

@Repository
public class UserDaoImpl implements IUserDao {

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}
	
	public User getUser(String login) {
		
		Session session = sessionFactory.getCurrentSession();
		
		User user = (User)session.get(User.class, login);
		if(user != null){
			Hibernate.initialize(user.getProfils());
			Hibernate.initialize(user.getEtablissement());
		}
		
		return user;
	}

	public void createUser(User user) {
		updateUser(user);
	}

	public void updateUser(User user) {
		Session session = sessionFactory.getCurrentSession();
		
		session.saveOrUpdate(user);
	}

	public void deleteUser(String login) {
		Session session = sessionFactory.getCurrentSession();
		
		User user = new User();
		user.setLogin(login);
		
		session.delete(user);
	}

	public List<User> getAllUsers() {

		List<User> users = new ArrayList<User>();
		
		Session session = sessionFactory.getCurrentSession();
		
		Query q = session.createQuery("From User");
		users = q.list();
		
		return users;
	}

	public List<ProfilUtilisateur> getProfils() {

		List<ProfilUtilisateur> profils = new ArrayList<ProfilUtilisateur>();
		
		Session session = sessionFactory.getCurrentSession();
		
		Query q = session.createQuery("From ProfilUtilisateur");
		profils = q.list();
		
		return profils;
	}
}
